#!/usr/bin/perl

use strict;
use warnings;

#my $filename="/home/ktang/projects/genome_stats/sordaria/feature_alignments/gb_sordaria.exon.stats.dat";
my $filename="gb_sordaria.exon.stats.dat";
my $FNAFILE;

open ($FNAFILE, '<', $filename)
    or die "Cannot open:$filename:$!";
my $header = <$FNAFILE>; # grab the first line of the file, it is a header 

my (@fh);
for my $num ( 1..22) {
#    my $filename = sprintf("/home/ktang/projects/genome_stats/sordaria/feature_alignments/sordaria.exon/gb_sordaria.exon%d.stats.dat",$num);
    my $outname = sprintf("gb_sordaria.exon%d.stats.dat",$num);
    open(my $fh => ">$outname") || die "cannot open $outname: $!";
    # print the header out for each of the files
    print $fh $header;
    # store the filehandle in the array
    push @fh, $fh;    
}

print "running  \n";

while(my $line = <$FNAFILE>)
{   
    chomp $line;
    if ($line =~ /exon\.(\d+)/ )
    {
	# this is the exon number
	my $exon_num = $1;
	# the entry in the array is num - 1 since exon.1 is stored in fh[0] 
	my $fh = $fh[$exon_num - 1];
	print $fh "$line\n"; 
    } 
}

close ($FNAFILE);
for my $fh ( @fh ) {
    close($fh);
}
